<template>
  <div id="app">
    <img alt="Vue logo" src="./assets/logo.png">
    <HelloWorld msg="Welcome to Your Vue.js App"/>
    <el-upload
        accept=".xls, .xlsx"
        action=""
        :limit="1"
        :http-request="handleChange"
        :file-list="fileList">
      <el-button size="small" type="primary">点击上传</el-button>
      <div slot="tip" class="el-upload__tip">只能上传.xls/xlsx文件</div>
    </el-upload>
  </div>
</template>

<script>
import HelloWorld from './components/HelloWorld.vue'

const XLSX = require('xlsx')

export default {
  name: 'App',
  components: {
    HelloWorld
  },
  data() {
    return {
      fileList: []
    }
  },
  methods: {
    async handleChange({file}) {
      // const fileExt = file.name.split('.').pop().toLocaleLowerCase()
      const dataBinary = await new Promise(resolve => {
        // Web API构造函数FileReader，可实例化对象，去调用其身上方法，去读取解析文件信息
        const reader = new FileReader()
        reader.readAsBinaryString(file)
        reader.onload = ev => {
          resolve(ev.target.result) // 将解析好的结果扔出去，以供使用
        }
      })
      try {
        const workBook = XLSX.read(dataBinary, {type: 'binary'})
        // excel中有很多的sheet，这里取了第一个sheet：workBook.SheetNames[0]
        console.log('=============', workBook.SheetNames)
        let result = [];
        for (let i = 0; i < workBook.SheetNames.length; i++) {
          let item = {
            routeNo: '',
            mainChargeList: []
          };
          const firstWorkSheet = workBook.Sheets[workBook.SheetNames[i]]
          // 分为第一行的数据，和第一行下方的数据
          const header = this.getHeaderRow(firstWorkSheet)
          console.log("读取的excel表头数据（第一行）", header);
          item.routeNo = header[14];
          const data = XLSX.utils.sheet_to_json(firstWorkSheet);
          item.mainChargeList = data.map(it => {
               return {
                 weightVolumeStart: it['GW/Vol_start'] || '',
                 weightVolumeEnd: it['GW/Vol_end'] || '',
                 currencyCode: it['Currency'] || '',
                 minPrice: it['M'] || null,
                 firstPrice: it['N'] || null,
                 secondaryPrice: it['45+'] || null,
                 thirdPrice: it['100+'] || null,
                 fourthPrice: it['300+'] || null,
                 fifthPrice: it['500+'] || null,
                 lastPrice: it['1000+']|| null
               }
          })
          result.push(item);
        }
        console.log("最终解析的数据=========", result);
      } catch (e) {
        console.log(e)
      }
    },
    getHeaderRow(sheet) {
      // 定义数组，用于存放解析好的数据
      const headers = []
      // 读取sheet的单元格数据
      const range = XLSX.utils.decode_range(sheet['!ref'])
      let C;
      const R = range.s.r
      for (C = range.s.c; C <= range.e.c; ++C) {
        /* walk every column in the range */
        const cell = sheet[XLSX.utils.encode_cell({c: C, r: R})]
        /* find the cell in the first row */
        // <-- replace with your desired default
        let hdr = 'UNKNOWN ' + C
        if (cell && cell.t) hdr = XLSX.utils.format_cell(cell)
        headers.push(hdr)
      }
      return headers
    }
  }
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>
